package com.cci.kangdao.cipFleet.service.impl;

import com.cci.kangdao.cipFleet.entity.ExternalCustomerESNT;
import com.cci.kangdao.cipFleet.service.ExternalCustomerESNTService;
import com.cci.kangdao.dao.DictionariesTDao;
import com.cci.kangdao.dao.EngineMasterDataMapper;
import com.cci.kangdao.dao.ExternalCustomerESNTMapper;
import com.cci.kangdao.dao.model.EngineMasterData;
import com.cci.kangdao.service.SyncEsnAndUserId;
import com.cci.kangdao.utilTool.BachUtil;
import com.cci.kangdao.utilTool.CollectionUtils;
import com.cci.kangdao.utilTool.LocalTimeUtil;
import net.sf.json.JSONArray;
import org.apache.commons.collections4.MapUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: joe
 * @company: CTY
 * @since: 2023/5/18 11:57
 * @version: V1.0
 **/
@Service
public class ExternalCustomerESNTServiceImpl implements ExternalCustomerESNTService {
    @Resource
    private ExternalCustomerESNTMapper externalCustomerESNTMapper;
    @Resource
    private EngineMasterDataMapper engineMasterDataMapper;
    @Resource
    private DictionariesTDao dictionariesTDao;

    @Resource
    private SyncEsnAndUserId syncEsnAndUserId;

    private Logger log = Logger.getLogger(this.getClass().getName());

    @Override
    @Transactional
    public Integer upholdUserIdESN(List<ExternalCustomerESNT> list, Integer type) {
//        if(type != 2) {
            int i = 0;
            //先将以前的数据删除
            if (CollectionUtils.isNotEmpty(list)) {
                log.error("upholdUserIdESN参数：" + JSONArray.fromObject(list).toString());
                Set<Integer> collect = list.stream().map(ExternalCustomerESNT::getUserId).collect(Collectors.toSet());
                //获取月度报告 删除的的list
                List<Map<String, Object>> paramListDelete = new ArrayList<>();
                List<ExternalCustomerESNT> externalCustomerSelect = externalCustomerESNTMapper.selectByUserIdListAndType(collect, type);
                if (CollectionUtils.isNotEmpty(externalCustomerSelect)) {
                    //同步数据至月度报告
                    Map<String, Object> mapReport = null;
                    for (ExternalCustomerESNT externalCustomerESNT : externalCustomerSelect) {
                        mapReport = new HashMap<>();
                        mapReport.put("ESN", externalCustomerESNT.getESN());
                        mapReport.put("userId", externalCustomerESNT.getUserId());
                        mapReport.put("originUserId", externalCustomerESNT.getUserId());
                        mapReport.put("originChannel", type);
                        paramListDelete.add(mapReport);
                    }
                }
                //删除历史的数据
                externalCustomerESNTMapper.deleteByUserIdList(collect, type, LocalTimeUtil.getRealCurrentTime());
                list.forEach(e -> {
                    e.setCreator(-1L);
                    e.setCreateTime(LocalTimeUtil.getRealCurrentTime());
                    e.setFlag(0);
                    e.setType(type);
                });
                //添加动力类型，应用类型
                List<String> esnList = list.stream().map(externalCustomerESNT -> externalCustomerESNT.getESN()).collect(Collectors.toList());
                List<EngineMasterData> engineMasterData = engineMasterDataMapper.selectByesnList(esnList);
                Map<String, EngineMasterData> map = new HashMap<>();
                if (CollectionUtils.isNotEmpty(engineMasterData)) {
                    map = engineMasterData.stream().collect(Collectors.toMap(EngineMasterData::getESN, t -> t));
                }
                List<Map<String, Object>> powerTypeDTableNameMap = dictionariesTDao.getDictionariesListByDTableName("fleetFuelType");
                Map<String, Integer> powerTypeMap = powerTypeDTableNameMap.stream().collect(Collectors.toMap(e -> MapUtils.getString(e, "DValue"), e -> MapUtils.getInteger(e, "DInt")));

                List<Map<String, Object>> applicationTypeDTableNameMap = dictionariesTDao.getDictionariesListByDTableName("fleetEmissionLevel");
                Map<String, Integer> applicationTypeMap = applicationTypeDTableNameMap.stream().collect(Collectors.toMap(e -> MapUtils.getString(e, "DValue"), e -> MapUtils.getInteger(e, "DInt")));
                for (ExternalCustomerESNT externalCustomerESNT : list) {
                    if (map.containsKey(externalCustomerESNT.getESN())) {
                        externalCustomerESNT.setType(type);
                        EngineMasterData engineMasterDataByMap = map.get(externalCustomerESNT.getESN());
                        if (powerTypeMap.containsKey(engineMasterDataByMap.getEngineFuelType())) {
                            externalCustomerESNT.setEsnPowerType(powerTypeMap.get(engineMasterDataByMap.getEngineFuelType()));
                        } else {
                            externalCustomerESNT.setEsnPowerType(null);
                        }
                        if (applicationTypeMap.containsKey(engineMasterDataByMap.getRelBulletinTelAboEmissionLevel())) {
                            externalCustomerESNT.setEsnApplicationType(applicationTypeMap.get(engineMasterDataByMap.getRelBulletinTelAboEmissionLevel()));
                        } else {
                            externalCustomerESNT.setEsnApplicationType(null);
                        }
                    } else {
                        externalCustomerESNT.setEsnPowerType(null);
                        externalCustomerESNT.setEsnApplicationType(null);
                    }
                }
                List<Object> bach = BachUtil.bach(list, externalCustomerESNTS -> {
                    int i1 = externalCustomerESNTMapper.insertList(externalCustomerESNTS);
                    return Arrays.asList(i1);
                });
                //同步数据至月度报告
                List<Map<String, Object>> paramListAdd = new ArrayList<>();
                if (CollectionUtils.isNotEmpty(list)) {
                    //同步数据至月度报告
                    Map<String, Object> mapReport = new HashMap<>();
                    for (ExternalCustomerESNT externalCustomerESNT : list) {
                        mapReport = new HashMap<>();
                        mapReport.put("ESN", externalCustomerESNT.getESN());
                        mapReport.put("userId", externalCustomerESNT.getUserId());
                        mapReport.put("plateNumber", externalCustomerESNT.getPlateNumber());
                        mapReport.put("drivingLicense", 0);
                        mapReport.put("originUserId", externalCustomerESNT.getUserId());
                        mapReport.put("originChannel", type);
                        //来源
                        mapReport.put("deviceSource", syncEsnAndUserId.deviceSourceConvert(String.valueOf(type)));
                        //渠道编号
                        mapReport.put("deviceChannel", "");
                        //渠道
                        mapReport.put("deviceOwner", "");
                        paramListAdd.add(mapReport);
                    }
                }
                // type  值必须与月度报告的值一致
                syncEsnAndUserId.asSyncEsnAndUserIdList(paramListAdd, new ArrayList<>(), paramListDelete, type);
            }
            return i;
//        }
//        return 0;
    }
}
